/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.controller;

import com.googlecode.bambole.domain.OrderItem;
import com.googlecode.bambole.controller.util.JsfUtil;
import com.googlecode.bambole.controller.util.PaginationUtil;
import com.googlecode.bambole.domain.OrderHeader;
import com.googlecode.bambole.domain.Product;
import com.googlecode.bambole.domain.User;
import com.googlecode.bambole.facade.OrderItemFacade;
import com.googlecode.bambole.util.DiscountUtil;

import java.io.Serializable;
import java.util.Date;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.inject.Inject;

@Named("orderItemController")
@SessionScoped
public class OrderItemController implements Serializable {

    private OrderItem current;
    private DataModel items = null;

    @EJB
    private com.googlecode.bambole.facade.OrderItemFacade ejbFacade;

    @EJB
    private com.googlecode.bambole.facade.OrderHeaderFacade orderHeaderFacade;

    @Inject
    private com.googlecode.bambole.controller.OrderHeaderController orderHeaderController;

    @Inject
    private com.googlecode.bambole.controller.ProductController productController;

    @Inject
    private com.googlecode.bambole.controller.ColorController colorController;

    private PaginationUtil pagination;
    private OrderHeader currentOrderHeader;
    private String query;
    private int selectedItemIndex;
    private int recordCount;

    public OrderItemController() {
    }

    public OrderItem getSelected() {
        if (current == null) {
            current = new OrderItem();
        }
        return current;
    }

    public void setSelected(OrderItem current) {
        this.current = current;
    }

    private OrderItemFacade getFacade() {
        return ejbFacade;
    }

    public boolean isPaginationFromSearch() {
        return !getQuery().equals(getDefaultQuery());
    }

    public PaginationUtil getPagination() {
        if (pagination == null) {
            pagination = new PaginationUtil(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count(getQuery(), currentOrderHeader);
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, getQuery(), currentOrderHeader));
                }
            };
        }
        return pagination;
    }

    public String refreshList() {
        query = null;
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareList() {
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareView() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        recordCount = getFacade().count(getQuery(), currentOrderHeader);

        return "view.xhtml?faces-redirect=true";
    }

    public String prepareCreate() {

        current = new OrderItem();
        current.setOrderHeader(currentOrderHeader);
        current.setEstimatedDeliveryDate(currentOrderHeader.getEstimatedDeliveryDate());

        return "create.xhtml?faces-redirect=true";
    }

    public String create() {

        if (!validateRecord()) {
            return null;
        }

        if (!updateCurrentOrderHeader()) {
            return null;
        }

        Date date = new Date();
        User user = (User) JsfUtil.getSessionParameter("user");
        current.setCreated(date);
        current.setCreatedBy(user);
        current.setUpdated(date);
        current.setUpdatedBy(user);

        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String prepareEdit() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));

            return null;
        }
        return "edit.xhtml?faces-redirect=true";
    }

    public String update() {

        if (!validateRecord()) {
            return null;
        }

        if (!updateCurrentOrderHeader()) {
            return null;
        }

        current.setUpdated(new Date());
        current.setUpdatedBy((User) JsfUtil.getSessionParameter("user"));

        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String destroy() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }
        performDestroy();
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            if (updateCurrentOrderHeader()) {
                JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordDeleted"));
            }
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public OrderItem getOrderItem(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex + pagination.getPageFirstItem();
    }

    public boolean isHasNextRecord() {
        return selectedItemIndex + 2 <= recordCount;
    }

    public boolean isHasPreviousRecord() {
        return selectedItemIndex > 0;
    }

    public String nextItem() {

        selectedItemIndex++;

        if (selectedItemIndex < recordCount) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery(), currentOrderHeader).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    public String previousItem() {

        selectedItemIndex--;

        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery(), currentOrderHeader).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    private boolean validateRecord() {

        boolean retVal = true;

        if (current.getOrderHeader().getStatus().isClosing()) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("ClosedOrdersCannotBeChanged"));

            retVal = false;
        }

        if (current.getPrice() <= 0) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PriceMustBeGreaterThanZero"));

            retVal = false;
        }

        if (current.getQty() <= 0) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("QuantityMustBeGreaterThanZero"));

            retVal = false;
        }

        return retVal;
    }

    private String getQuery() {
        return query == null ? getDefaultQuery() : query;
    }

    private String getDefaultQuery() {
        return "SELECT o FROM OrderItem o WHERE o.orderHeader = :orderHeader";
    }

    public OrderHeader getCurrentOrderHeader() {
        return currentOrderHeader;
    }

    public void setCurrentOrderHeader(OrderHeader orderHeader) {
        currentOrderHeader = orderHeader;
        query = getDefaultQuery();
        recreatePagination();
        recreateModel();
    }

    public String prepareCurrentOrderHeaderView() {
        if (updateCurrentOrderHeader()) {
            orderHeaderController.setSelected(currentOrderHeader);
            return "/app/order_header/view.xhtml?faces-redirect=true";
        } else {
            return null;
        }
    }

    private boolean updateCurrentOrderHeader() {
        if (currentOrderHeader == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return false;
        }

        double productAmount = getFacade().getProductAmount(currentOrderHeader);
        double totalAmount = getFacade().getTotalAmount(currentOrderHeader);
        double orderHeaderAmount = DiscountUtil.calculateAmount(totalAmount, currentOrderHeader.getDiscount());

        currentOrderHeader.setOrderItemList(getFacade().findByOrderHeader(currentOrderHeader));
        currentOrderHeader.setProductAmount(productAmount);
        currentOrderHeader.setDiscountedProductAmount(totalAmount);
        currentOrderHeader.setAmount(orderHeaderAmount);
        currentOrderHeader.setProductDiscount(DiscountUtil.calculateDiscount(productAmount, totalAmount));
        currentOrderHeader.setTotalDiscount(DiscountUtil.calculateDiscount(productAmount, orderHeaderAmount));

        try {
            orderHeaderFacade.edit(currentOrderHeader);
            return true;
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return false;
        }
    }

    public SelectItem[] getSelectProduct() {
        return productController.getItemsAvailableSelectOne(false);
    }

    public SelectItem[] getSelectColor() {
        return productController.getColorsAvailableSelectOne(current.getProduct());
    }

    public void productUpdate(ValueChangeEvent e) {
        current.setProduct((Product) e.getNewValue());
        current.setColor(null);
        current.setQty(0);
        current.setDiscount(0.0);
        current.setProductPrice(current.getProduct() == null ? 0 : current.getProduct().getPrice());
        current.setPrice(current.getProduct() == null ? 0 : current.getProduct().getPrice());
        current.setAmount(current.getProduct() == null ? 0 : current.getPrice() * current.getQty());
    }

    public void qtyUpdate(ValueChangeEvent e) {
        current.setAmount(current.getPrice() * ((Long) e.getNewValue()).intValue());
    }

    public void priceUpdate(ValueChangeEvent e) {
        double newPrice;
        if (e.getNewValue() instanceof Long) {
            newPrice = ((Long) e.getNewValue()).doubleValue();
        } else {
            newPrice = (Double) e.getNewValue();
        }
        current.setAmount(current.getQty() * newPrice);
        current.setDiscount(DiscountUtil.calculateDiscount(current.getProductPrice(), newPrice));
    }

    public void discountUpdate(ValueChangeEvent e) {
        double newDiscount;
        if (e.getNewValue() instanceof Long) {
            newDiscount = ((Long) e.getNewValue()).doubleValue();
        } else {
            newDiscount = (Double) e.getNewValue();
        }
        current.setPrice(DiscountUtil.calculateAmount(current.getProductPrice(), newDiscount));
        current.setAmount(current.getQty() * current.getPrice());
    }

    public String getFormattedTotalAmount() {
        return String.format(JsfUtil.getLocale(), "%,.2f", getFacade().getTotalAmount(currentOrderHeader));
    }

    @FacesConverter(forClass = OrderItem.class)
    public static class OrderItemControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            OrderItemController controller = (OrderItemController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "orderItemController");
            return controller.getOrderItem(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof OrderItem) {
                OrderItem o = (OrderItem) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + OrderItem.class.getName());
            }
        }

    }

}
